package com.liang.subject.domain.handler.subject;

import com.google.common.base.Preconditions;
import com.liang.subject.common.enums.SubjectInfoTypeEnum;
import com.liang.subject.domain.convert.RadioSubjectConverter;
import com.liang.subject.domain.entity.SubjectAnswerBO;
import com.liang.subject.domain.entity.SubjectInfoBO;
import com.liang.subject.domain.entity.SubjectOptionBO;
import com.liang.subject.infra.basic.entity.SubjectRadio;
import com.liang.subject.infra.basic.service.SubjectRadioService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 单选题目策略类
 */
@Component
@RequiredArgsConstructor
public class RadioTypeHandler implements SubjectTypeHandler {

    private final SubjectRadioService subjectRadioService;

    @Override
    public SubjectInfoTypeEnum getSubjectType() {
        return SubjectInfoTypeEnum.RADIO;
    }

    @Override
    public void save(SubjectInfoBO subjectInfoBO) {
        // 单选题目的插入
        List<SubjectRadio> radioList = new ArrayList<>();
        List<SubjectAnswerBO> optionList = subjectInfoBO.getOptionList();
        Preconditions.checkNotNull(optionList, "选项列表不能为空");
        optionList.stream().forEach(option -> {
            SubjectRadio subjectRadio = RadioSubjectConverter.INSTANCE.convertBO2PO(option);
            subjectRadio.setSubjectId(subjectInfoBO.getId());
            radioList.add(subjectRadio);
        });
        subjectRadioService.saveBatch(radioList);
    }

    @Override
    public SubjectOptionBO querySubjectInfo(Long subjectId) {
        List<SubjectRadio> radioList = subjectRadioService.listBySubjectId(subjectId);
        List<SubjectAnswerBO> subjectAnswerBOList = RadioSubjectConverter.INSTANCE.convert2BOList(radioList);
        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        subjectOptionBO.setOptionList(subjectAnswerBOList);
        return subjectOptionBO;
    }
}
